package array;

//最大子数组和
public class leetcode53 {
    public static void main(String[] args) {
        int[] nums = {-2,1,-3,4,-1,2,1,-5,4};
        int result = maxSubArray2(nums);
        System.out.print(result);
    }

    public static int maxSubArray(int[] nums){
        int result = nums[0];
        int[] array = new int[nums.length];
        for (int i = 0; i < array.length; i++) {
            array[i] = 0;
        }

        for (int i = 0; i < nums.length; i++) {
            array[i] = nums[i];
            if(i>0) {
                for (int j = 0; j < i; j++) {
                    array[j] += array[i];
                    if(array[j] > result){
                        result = array[j];
                    }
                }
            }
        }

        return result;
    }

    public static int maxSubArray2(int[] nums){
        if(nums.length==0){
            return 0;
        }

        int res = nums[0];
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            dp[i] = Math.max(dp[i-1] + nums[i], nums[i]);
            res = res > dp[i] ? res : dp[i];
        }

        return res;
    }
}
